<template>
  <div>
    <el-dialog
      title="关联商品"
      :visible="visible"
      :modal-append-to-body="false"
      width="60%"
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-row>
        <el-form ref="searchData" :model="searchData" label-width="95px">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="SPU编码" label-position="right" prop="spuNo">
                <el-input
                  v-model="searchData.spuNo"
                  placeholder="请输入SPU编码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="供应商编码"
                label-position="right"
                prop="supplyUuid"
              >
                <el-input
                  v-model="searchData.supplyUuid"
                  placeholder="请输入供应商编码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="商品名称"
                label-position="right"
                prop="productName"
              >
                <el-input
                  v-model="searchData.productName"
                  placeholder="请输入商品名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" v-if="this.pageType">
              <el-form-item
                label="SKU编码"
                label-position="right"
                prop="skuNoBy"
              >
                <el-input
                  v-model="searchData.skuNoBy"
                  placeholder="请输入SKU编码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!this.pageType">
              <el-form-item label="SKU编码" label-position="right" prop="skuNo">
                <el-input
                  v-model="searchData.skuNo"
                  placeholder="请输入SKU编码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="供应商名称"
                label-position="right"
                prop="supplyName"
              >
                <el-input
                  v-model="searchData.supplyName"
                  placeholder="请输入供应商名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!this.pageType">
              <el-form-item
                label="规格"
                label-position="right"
                prop="specDetail"
              >
                <el-input
                  v-model="searchData.specDetail"
                  placeholder="请输入规格"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!this.pageType">
              <el-form-item
                label="销售区域"
                label-position="right"
                prop="saleArea"
              >
                <el-input
                  v-model="searchData.saleArea"
                  placeholder="请输入销售区域"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="!this.pageType">
              <el-form-item
                label="销售省"
                label-position="right"
                prop="saleProvince"
              >
                <el-input
                  v-model="searchData.saleProvince"
                  placeholder="请输入销售省"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-row type="flex" justify="end" class="btns-wrap">
        <el-button
          type="primary"
          @click="handleQueryData('')"
          :disabled="tabpaneDisabled"
          >查询</el-button
        >
        <el-button @click="handleQueryData('reset')" :disabled="tabpaneDisabled"
          >清空</el-button
        >
        <el-button
          v-if="tabsStatus == 'notAssociated'"
          type="primary"
          ghost
          @click="handleBatchAssociate('1')"
          :disabled="tabpaneDisabled"
          >批量关联</el-button
        >
        <el-button
          v-else
          ghost
          @click="handleBatchAssociate('2')"
          :disabled="tabpaneDisabled"
          >批量取消</el-button
        >
      </el-row>
      <el-tabs
        v-model="tabsStatus"
        @tab-click="handleTabChange"
        style="margin: 10px"
      >
        <el-tab-pane
          label="未关联"
          name="notAssociated"
          :disabled="tabpaneDisabled"
        >
        </el-tab-pane>
        <el-tab-pane
          label="已关联"
          name="isAssociated"
          :disabled="tabpaneDisabled"
        >
        </el-tab-pane>
      </el-tabs>
      <pl-table
        ref="multipleTable"
        size="mini"
        :row-height="45"
        border="border"
        use-virtual
        height="480"
        v-loading="tableLoading"
        :data="tableData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleCheckboxSelect"
      >
        <!-- <pl-table-column fixed type="selection" width="50" /> -->
        <template v-for="item in column">
          <pl-table-column
            :key="item.key"
            :prop="item.key"
            :label="item.title"
            :property="item.key"
            :align="item.align"
            :min-width="100"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :type="item.type"
          >
            <template v-if="item.slot === 'action'" v-slot="scope">
              <el-button
                v-if="tabsStatus === 'notAssociated'"
                type="success"
                size="mini"
                @click="handleAssociateGoods(scope.row, scope.$index)"
                >关联</el-button
              >
              <el-button
                v-else
                size="mini"
                @click="handleCancelGoods(scope.row, scope.$index)"
                >取消</el-button
              >
            </template>
          </pl-table-column>
        </template>
      </pl-table>
      <div class="pagination_wrap">
        <el-pagination
          background
          :total="totalPage"
          :current-page="pageNation.nowPage"
          :page-size="pageNation.pageShow"
          :page-sizes="pageSizeOpts"
          @current-change="handleChangePage"
          @size-change="handleChangePageSize"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
      <el-row slot="footer" style="text-align: center">
        <el-button type="primary" @click="handleCloseModal">返回表单</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
export default {
  components: {},
  props: {
    dialogVisible: false,
    // 0 修改进价 1 修改供货信息
    pageType: 0,
    goodsType: '',
    column: {
      type: Array,
      default: () => {
        return []
      }
    },
    skuRows: {
      type: Array,
      default: () => {
        return []
      }
    },
    maxLinkedNum: {
      type: Number
    }
  },
  data () {
    return {
      pageSizeOpts: [10, 100, 500, 1000],
      tabpaneDisabled: false,
      searchData: {
        skuNoBy: '',
        skuNo: '',
        productName: '',
        spuNo: '',
        supplyUuid: '', // 供应商编码 - 模糊查询
        supplyName: '', // 供应商名称 - 模糊查询
        specDetail: '', // 规格
        saleProvince: '', // 销售省
        saleArea: '', // 销售区域
      },
      tableData: [], // 商品列表
      tabsStatus: 'notAssociated',
      tableLoading: false,
      selectCheckboxList: [],
      pageNation: {
        nowPage: 1,
        pageShow: 10
      },
      totalPage: 0
    };
  },
  computed: {
    hasSelectSkuRows () {
      return this.skuRows;
    },
    visible () {
      return this.dialogVisible;
    }
  },
  methods: {
    getLinkData () {
      if (this.pageType) {
        this.getLinkDataForSupply();
      } else {
        this.getLinkDataForPurchasePrice();
      }
    },

    // 点击查询 清空
    handleQueryData (type) {
      if (type == 'reset') {
        this.$refs['searchData'].resetFields();
      } else {
        // 查询
        this.getLinkData();
      }
    },

    // tab切换 关联与未关联
    handleTabChange () {
      this.selectCheckboxList = [];
      const { pageShow } = this.pageNation;
      this.pageNation = {
        nowPage: 1,
        pageShow
      };
      this.getLinkData();
    },

    // 未关联列表多选
    handleCheckboxSelect (arr) {
      this.selectCheckboxList = arr;
    },

    // 关闭弹框
    handleCloseModal () {
      if (this.maxLinkedNum && this.hasSelectSkuRows.length > this.maxLinkedNum) {
        return this.$message.warning(`最大关联数量不超过${this.maxLinkedNum}`);
      }
      if (this.pageType) {
        let skuNos = [];
        let supplyCode = [];
        this.hasSelectSkuRows.forEach((item) => {
          skuNos.push(item.skuNo);
          if (item.supplyUuid) {
            supplyCode.push(item.supplyUuid);
          } else {
            supplyCode.push(item.supplierCode);
          }
        });
        let params = {
          skuNos: [...new Set(skuNos)],
          supplyCode: [...new Set(supplyCode)]
        };
        this.$emit('returnList', params);
      } else {
        let uuids = this.hasSelectSkuRows.map(item => item.uuid);
        this.$emit('returnList', uuids);
      }
    },

    // 关联
    handleAssociateGoods (row) {
      this.$emit('addSkuRows', row);
      this.$nextTick(() => {
        this.getLinkData();
        this.$Message.success('关联成功');
      });
    },

    // 取消关联
    handleCancelGoods (row) {
      this.$emit('removeSkuRows', row);
      this.$nextTick(() => {
        this.getLinkData();
        this.$Message.success('取消成功');
      });
    },
    // 批量操作  1批量关联  2 批量取消
    handleBatchAssociate (num) {
      if (this.selectCheckboxList.length == 0) {
        return this.$Message.warning('请选择要关联的商品');
      }
      if (num == 1) {
        this.selectCheckboxList.forEach((item) => {
          this.$emit('addSkuRows', item);
        });
      } else {
        this.selectCheckboxList.forEach((item) => {
          this.$emit('removeSkuRows', item);
        });
      }
      this.$nextTick(() => {
        this.getLinkData();
        this.$Message.success('操作成功');
      });
    },

    // 获取修改进价关联商品列表
    getLinkDataForPurchasePrice () {
      let uuids = [];
      this.hasSelectSkuRows.forEach((item) => {
        uuids.push(item.uuid);
      });
      const params = {
        ...this.searchData,
        ...this.pageNation,
        uuidList: uuids, // 已关联的进价数据uuid，查询已关联未关联都得传，为空不用传
        isPurchaseMultiUnit: this.goodsType, // 1多计量 2单计量
        isQueryRel: this.tabsStatus != 'notAssociated', // true:已关联/false:未关联
      }

      this.tableLoading = true;
      this.tabpaneDisabled = true;
      ApiRequest(
        // '/sysback/supplyskurel/getSupplySkuRelList',
        '/sysback/supplyskurel/getSupplySkuPriceRelList',
        'post',
        params,
        false
      )
        .then((res) => {
          if (res.retStatus == '1' && res.retData.results != null) {
            this.totalPage = res.retData.totalNum;
            this.tableData = res.retData.results;
          }
          this.tableLoading = false;
          this.tabpaneDisabled = false;
        })
        .catch(() => {
          this.tableLoading = false;
          this.tabpaneDisabled = false;
        });
    },
    // 获取供货信息可关联商品列表
    getLinkDataForSupply () {
      let uuids = [];
      this.hasSelectSkuRows.forEach((item) => {
        uuids.push(item.uuid);
      });
      let url = '';
      let param = [
        {
          name: 'productName',
          value: this.searchData.productName
        },
        {
          name: 'spuNo',
          value: this.searchData.spuNo
        },
        {
          name: 'skuNo',
          value: this.searchData.skuNoBy
        },
        {
          // "name": "supplyNo",
          name: 'supplyUuid',
          value: this.searchData.supplyUuid
        },
        {
          name: 'supplyName',
          value: this.searchData.supplyName
        }
      ];
      if (this.tabsStatus == 'notAssociated') {
        url = '/sysback/supplyskurel/getNoRelSkuListForUpdate';
        param.push(
          /* {
            "name": "skuNoNotInListStr",
            "value": skuNos.join(','),
          } */
          {
            name: 'uuidNotInListStr',
            value: uuids.join(',')
          }
        );
      } else {
        url = '/sysback/supplyskurel/getRelSkuListForUpdate';
        param.push(
          /* {
            "name": "skuNoListStr",
            "value": skuNos.join(','),
          } */
          {
            name: 'uuidListStr',
            value: uuids.join(',')
          }
        );
      }

      const { nowPage, pageShow } = this.pageNation;
      let data = {
        sortName: '',
        sortType: '',
        searchParam: JSON.stringify(param),
        nowPage,
        pageShow
      };
      this.tableLoading = true;
      this.tabpaneDisabled = true;
      ApiRequest(url, 'post', data, false).then((res) => {
        this.tableLoading = false;
        this.tabpaneDisabled = false;
        if (res.retStatus == '1') {
          this.tableData = res.retData.results;
          this.totalPage = res.retData.totalNum;
        }
      });
    },

    handleChangePage (pageNum) {
      const { pageShow } = this.pageNation;
      this.pageNation = {
        nowPage: pageNum,
        pageShow
      };
      this.getLinkData();
    },

    handleChangePageSize (pageSize) {
      this.pageNation = {
        nowPage: 1,
        pageShow: pageSize
      };
      this.getLinkData();
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-dialog__body {
  padding: 10px 20px;
}
/deep/ .el-dialog__header {
  border-bottom: 1px solid #e8eaec;
}
/deep/ .el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
/* 查询清空批量操作栏样式 */
.options_wrap {
  /deep/ .ivu-btn {
    margin-left: 15px;
  }
  /deep/ .ivu-btn-ghost {
    margin-right: 10px;
  }
}

/* 分页样式 */
.pagination_wrap {
  text-align: center;
  margin-top: 10px;
}
</style>
